package cn.buk.tms.flight.service;

import cn.buk.common.JsonResult;
import cn.buk.common.sc.CommonSearchCriteria;
import cn.buk.tms.entity.misc.FlightKeyCustomerPolicy;
import cn.buk.tms.entity.misc.RoleInfo;
import cn.buk.qms.service.BaseAbstractService;
import cn.buk.tms.flight.dao.KeyCustomerPolicyDao;
import cn.buk.tms.flight.dto.KeyCustomerPolicyDto;
import cn.buk.tms.util.ValidationUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yfdai
 */
@Service
public class FlightKeyCustomerPolicyServiceImpl extends BaseAbstractService implements FlightKeyCustomerPolicyService {

  @Autowired
  public FlightKeyCustomerPolicyServiceImpl(KeyCustomerPolicyDao keyCustomerPolicyDao) {
    this.keyCustomerPolicyDao = keyCustomerPolicyDao;
  }

  private final KeyCustomerPolicyDao keyCustomerPolicyDao;

  @Override
  @Secured({RoleInfo.ROLE_DATA_ADMIN, RoleInfo.ROLE_ADMIN})
  public JsonResult saveKeyCustomerPolicy(int enterpriseId, KeyCustomerPolicyDto dto) {
    try {
      ValidationUtils.validate(dto);
    } catch (RuntimeException ex) {
      return JsonResult.createJsonResult(-1, ex.getMessage());
    }

    FlightKeyCustomerPolicy obj = new FlightKeyCustomerPolicy();
    BeanUtils.copyProperties(dto, obj);
    obj.setEnterpriseId(enterpriseId);

    try {
      int retCode = keyCustomerPolicyDao.saveKeyCustomerPolicy(obj);
      return JsonResult.createJsonResult(retCode);
    } catch (RuntimeException ex) {
      return JsonResult.createJsonResult(-100, ex.getMessage());
    }
  }

  @Override
  public List<KeyCustomerPolicyDto> searchKeyCustomerPolicies(int enterpriseId, CommonSearchCriteria sc) {
    List<FlightKeyCustomerPolicy> policies = keyCustomerPolicyDao.search(enterpriseId, sc);

    List<KeyCustomerPolicyDto> dtos = new ArrayList<>();
    for(FlightKeyCustomerPolicy policy: policies) {
      KeyCustomerPolicyDto dto = new KeyCustomerPolicyDto();
      BeanUtils.copyProperties(policy, dto);

      dtos.add(dto);
    }

    return dtos;
  }
}
